<template>
  <div class="goods-type" ref="typeBoxRef" @click.stop="() => { }">
    <template v-for="type in goodsTypeList" :key="type.id">
      <div v-if="typeOutShow(type.name)" class="goods-type__item" :class="{ active: selectedTypeId == type.id }">
        <template v-if="type.children && type.children.length">
          <div class="goods-type__item--title">{{ type.name }}</div>
          <div class="goods-type__item--body">
            <template v-for="(item, index) in type.children" :key="index">
              <el-divider v-if="typeOutShow(item.name) && index" direction="vertical" />
              <span v-if="typeOutShow(item.name)" class="goods-type__route--item"
                @click="handleRouteClick($event, item, type)" :class="{ active: selectedId == item.id }">{{ item.name
                }}</span>
            </template>
          </div>
        </template>
        <template v-else>
          <div class="goods-type__item--title">
            <span v-if="typeOutShow(type.name)" class="goods-type__route--item" @click="handleRouteClick($event, type)"
              :class="{ active: selectedId == type.id }">{{ type.name }}
            </span>
          </div>
        </template>
      </div>
    </template>
    <transition name="el-zoom-in-center">
      <div v-show="show" class="goods-type__other" :style="styleObj">
        <el-menu class="jbc-type" :default-active="activeIndex" @select="bindSelect">
          <goods-type-children v-for="(type, index) in selectedChildren" :key="type.id + index"
            :item="type"></goods-type-children>
        </el-menu>
      </div>
    </transition>
  </div>
</template>

<script setup name="goodsType">
import { appIndexGetTypesGet } from '@/api/common'
import { handleTree } from '@/utils/ruoyi'
import goodsTypeChildren from './goodsTypeChildren'
import { nextTick, computed } from "vue"
const props = defineProps({
  typePage: Boolean,
  typeId: String
})
const router = useRouter()
const route = useRoute()
const emit = defineEmits(['change'])
const typeBoxRef = ref(null)
const goodsTypeList = ref([])
const typeData = ref([])
const show = ref(false)
const selectedTypeId = ref('')
const selectedId = ref('')
const selectedChildren = ref([])
const activeIndex = ref('')
const selectedPath = ref([])
const styleObj = ref({
  top: '0px'
})
const typeOutShow = computed(() => {
  let t = route.name === 'shop' && route.params.id === '1' ? true : false
  return (v) => {
    return !t ? true : v !== '物料' && v !== '周边' ? true : false


  }
})
const cancel = () => {
  if (show.value) {
    show.value = false
    selectedTypeId.value = ''
    selectedId.value = ''
    selectedChildren.value = []
    activeIndex.value = ''
    selectedPath.value = []
    emitChange('', [])
  }
}
appIndexGetTypesGet().then((res) => {
  if (res.data) {
    res.data.forEach(it => {
      it.label = it.name
      it.value = it.id
    })
  } else {
    res.data = []
  }
  typeData.value = res.data
  goodsTypeList.value = handleTree(res.data, 'id', 'pid')
  if (props.typeId) {
    setDefault(props.typeId)
  }
}).catch((err) => {
  console.log(err)
})
const handleRouteClick = (e, item, type) => {
  const { x, y } = getRelativePosition(e.target, typeBoxRef.value)
  console.log(x, y)
  if (type && item.children && item.children.length > 0) { // 存在type 且有子分类
    selectedChildren.value = item.children
    styleObj.value.top = `${y}px`; // 设置下拉菜单的位置

    if (selectedId.value !== item.id) { // 选中id不同
      selectedId.value = item.id
      selectedTypeId.value = type.id
      activeIndex.value = ''
    } else {
      activeIndex.value = props.typeId
    }
    nextTick(() => {
      show.value = true
    })
  } else if (type && !item.children) { // 存在type 但无子分类 即二级就是叶子节点
    show.value = false
    selectedId.value = item.id
    selectedTypeId.value = type.id
    activeIndex.value = ''
    nextTick(() => {
      selectedChildren.value = []
      emitChange(item.id, [type.id, item.id])
    })
  } else { // 不存在type 即一级就是叶子节点
    show.value = false;
    selectedId.value = item.id
    selectedTypeId.value = item.id
    activeIndex.value = ''
    nextTick(() => {
      selectedChildren.value = []
      emitChange(item.id, [item.id])
    })
  }
};
const bindSelect = (key, keyPath) => {
  activeIndex.value = key;
  keyPath.unshift(selectedId.value)
  keyPath.unshift(selectedTypeId.value)
  show.value = false
  emitChange(key, keyPath)
}
const emitChange = (id, path) => {
  const pathIndex = {}
  const pathList = JSON.parse(JSON.stringify(typeData.value.filter((item) => path.indexOf(item.id) > -1)))
  path.forEach((item, index) => {
    pathIndex[item] = index
  })
  pathList.sort((a, b) => pathIndex[a.id] - pathIndex[b.id])
  selectedPath.value = pathList
  emit('change', { id, pathList })
  const queryData = {}
  if (route.query.searchKey) {
    queryData.searchKey = route.query.searchKey
  }
  if (id) {
    queryData.typeId = id
  }
  if (route.name === 'type') {
    router.push({
      path: `/type`,
      query: queryData,
      replace: true
    })
  } else if (route.name === 'shop') {
    router.push({
      name: 'shop',
      query: queryData,
      params: { id: route.params.id },
      replace: true
    })
  } else {
    router.push({
      path: `/type`,
      query: queryData
    })
  }
}
const getParentPath = (pid, path = []) => {
  const parent = typeData.value.find(it => it.id == pid)
  if (parent) {
    path.unshift(parent)
    getParentPath(parent.pid, path)
  }
}
const setDefault = (id) => {
  if (id && typeData.value.length > 0) {
    const item = typeData.value.find(it => it.id === id)
    const pathList = [item]
    getParentPath(item.pid, pathList)
    activeIndex.value = id
    selectedPath.value = pathList
    if (pathList.length > 2) {
      selectedTypeId.value = pathList[0].id
      selectedId.value = pathList[1].id
      selectedChildren.value = pathList[2].children
    } else if (pathList.length === 2) {
      selectedTypeId.value = pathList[0].id
      selectedId.value = pathList[1].id
      selectedChildren.value = []
    } else if (pathList.length === 1) {
      selectedId.value = id
      selectedTypeId.value = id
      selectedChildren.value = []
    }
    emit('change', { id, pathList })
  } else {
    show.value = false
    selectedTypeId.value = ''
    selectedId.value = ''
    selectedChildren.value = []
    activeIndex.value = ''
    selectedPath.value = []
    emit('change', { id: '', pathList: [] })
  }
}
const idWatch = watch(
  () => props.typeId,
  (v) => {
    setDefault(v)
  }
)
function getRelativePosition (childElement, parentElement) {
  // 获取子元素的边界矩形
  const childRect = childElement.getBoundingClientRect();
  // 获取父元素的边界矩形
  const parentRect = parentElement.getBoundingClientRect();
  // 计算子元素相对于父元素的 x 坐标
  const x = childRect.left - parentRect.left;
  // 计算子元素相对于父元素的 y 坐标
  const y = childRect.top - parentRect.top;
  return { x, y };
}
onMounted(() => {
  window.addEventListener('click', cancel)
})
onBeforeUnmount(() => {
  window.removeEventListener('click', cancel)
})
</script>

<style lang="scss" scoped>
.goods-type {
  position: relative;
  width: 270px;
  background-color: #fafafa;
  font-size: var(--el-font-size-base);

  &__item {
    width: 100%;
    padding: 13px 20px;

    &.active,
    &:hover {
      background-color: #F2F2F2;
    }

    &--title {
      font-weight: bold;
      font-size: 16px;
      color: var(--jbc-font-color);
      line-height: 21px;
      margin-bottom: 7px;
    }

    &--body {
      color: var(--jbc-font-color-light);
      line-height: 30px;
    }
  }

  &__route--item {
    display: inline-block;
    cursor: pointer;

    &.active {
      color: var(--jbc-color);
    }
  }

  &__other {
    position: absolute;
    width: 230px;
    top: 0;
    left: 270px;
    z-index: 9999999;
    --el-menu-item-height: 40px;

    .jbc-type {
      border: 1px solid var(--jbc-color);
      --el-menu-text-color: var(--jbc-font-color);
      --el-menu-hover-text-color: var(--jbc-font-color);
      --el-menu-active-color: var(--jbc-color);
    }
  }
}
</style>